package com.code.aicodemother.core;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.code.aicodemother.ai.model.HtmlCodeResult;
import com.code.aicodemother.ai.model.MultiFileCodeResult;
import com.code.aicodemother.model.enums.CodeGenTypeEnum;

import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * 代码文件保存器
 */
@Deprecated
public class CodeFileSaver {
    // 代码文件保存目录
    private static final String FILE_SAVE_ROOT_DIR= System.getProperty("user.dir") + "/tmp/code_output/";
    /**
     * 保存HTML代码文件
     */
    public static File saveHtmlCodeResult(HtmlCodeResult htmlCodeResult) {
        String dirPath=buildUniqueDir(CodeGenTypeEnum.HTML.getValue());
        WireToFile(dirPath,"index.html",htmlCodeResult.getHtmlCode());
        return new File(dirPath);
    }

    /**
     * 保存MultiFile代码文件
     */
    public static File saveMultiFileCodeResult(MultiFileCodeResult multiFileCodeResult) {
        String dirPath=buildUniqueDir(CodeGenTypeEnum.MULTI_FILE.getValue());
        WireToFile(dirPath,"index.html",multiFileCodeResult.getHtmlCode());
        WireToFile(dirPath,"style.css",multiFileCodeResult.getCssCode());
        WireToFile(dirPath,"script.js",multiFileCodeResult.getJsCode());
        return new File(dirPath);
    }

    /**
     * 构建唯一目录路径：tmp/code_output/bizType_雪花ID
     */
    private static String buildUniqueDir(String bizType) {
        String uniqueDirName = StrUtil.format("{}_{}", bizType, IdUtil.getSnowflakeNextIdStr());
        String dirPath=FILE_SAVE_ROOT_DIR+ File.separator+uniqueDirName;
        FileUtil.mkdir(dirPath);
        return dirPath;

    }


    /**
     * 写入单个文件
     */
    private static void WireToFile(String dirPath, String fileName, String content) {
        String filePath = dirPath + File.separator + fileName;
        FileUtil.writeString(content,filePath, StandardCharsets.UTF_8);
    }
}
